<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use App\Model\Guild\GuildHost;
use App\Model\GuildManage;
use App\Model\Message;
use App\Model\Stat\StatDailyHostInfo;
use App\Model\User;
use App\Model\UserProfile;
use App\Util\ComUtil;
use App\Util\InfoUtil;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Illuminate\Support\Facades\Log;
use App\Model\UsersRating;

class HostCateController extends Controller
{
    use ModelForm;

    /**
     * 用户列表
     *
     * @return Content
     */
    public function index()
    {
        $this->adminId = Admin::user()->id;
        return Admin::content(function (Content $content) {
            $content->header('女用户评级');
            $content->description('收入单位：金币');
            $content->body($this->grid());
        });
    }

    /**
     * 用户编辑
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {
            $content->header('编辑');
            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {
            $content->header('添加');
            $content->description('');
            $content->body($this->form());
        });
    }

    /**
     * 用户编辑
     * @return Form
     */
    protected function form()
    {
        return Admin::form(UserProfile::class, function (Form $form) {

            $inputs = request()->input();

            if($inputs['name'] == 'users_rating_item.grade'){
                $profile = UserProfile::getProfileById($inputs['pk']);

                UsersRating::updateGrade($profile->user_id,$inputs['value']);
            }

            // $form->display('id', '用户内部ID');
            $form->text('host_cate', '评级');
            $form->text('host_share', '分成');
            $form->text('host_mark', '标签');
            $form->text('user_id', '用户ID');
            $form->text('video_coin_setting', '视频');
            $form->text('coin_setting', '语音');
            $form->text('chat_coin_setting', '私信');
            $form->saving(function (Form $form) {
                if ($form->video_coin_setting > 200) {
                    throw new \Exception('最高可设置视频：200金币');
                }
                if ($form->chat_coin_setting > 20) {
                    throw new \Exception('最高可设置私信：20金币');
                }
                if ($form->coin_setting > 150) {
                    throw new \Exception('最高可设置语音：150金币');
                }
                if (!$form->host_share) return;
                $model = $form->model();
                $hostId = $model->user_id;
                //指定代理下不发通知
                if (in_array(GuildHost::getGuildId($hostId), [0])) return;
                $percent = ($form->host_share * 100) . "%";
                $msg = "亲爱的用户：你好！
根据你最近的活跃及收入等情况。现在系统将你的收益比例自动调整为{$percent}，请继续保持活跃在线、提升收入、提高接通率及接听时长等关键指标，即可获得更高的分成比例。

如需咨询或调整分成比例，请添加客服微信了解详情（微信号： kefuweixin333）";
                Message::pushSystem($model->user_id, $msg, '收益调整通知');
                Log::info(__CLASS__ . "==NewShare:{$form->host_share}==OldShare:{$model->host_share}==UserId:{$model->user_id}");
            });
        });
    }

    /**
     * 声优列表
     * @return Grid
     */
    protected function grid()
    {
        $guildHosts = GuildHost::getAllHosts();
        // echo request('cal_duration');
        $adminId = Admin::user()->id;

        $grid = new Grid(new UserProfile());
        $where = [
            ['role', UserProfile::ROLE_HOST]
        ];
        if(in_array($adminId,[50,51])) {
            $guidIds = GuildManage::getGuidIdByAdminId($adminId);
            $hostIds = GuildHost::getHostUidByAdminId($guidIds);
            $grid->model()->where($where)->whereIn('user_id',$hostIds)->orderBy('charm_value', 'desc');
        }else{
            $grid->model()->where($where)->orderBy('charm_value', 'desc');
        }

        $grid->avatar('头像')->display(function ($data) {
            if (!$data) return '';
            return ComUtil::buidlImgaeHtml($data);
        });
        $grid->user_profile_id('ID')->sortable();
        $grid->user_id('内部ID')->sortable();
        $grid->nick_name('昵称');
//        $grid->is_guild('是否代理女用户')->display(function ($data) use ($guildHosts) {
//            return isset($guildHosts[$this->user_id]) ? $guildHosts[$this->user_id] : '';
//        });
        // if ($this->adminId == 1) {
        $grid->coin_setting('语音收费设置')->editable();
        $grid->video_coin_setting('视频收费设置')->editable();
        $grid->chat_coin_setting('私聊收费设置')->editable();
        // } else {
        //     $grid->coin_setting('语音收费设置');
        //     $grid->video_coin_setting('视频收费设置');
        //     $grid->chat_coin_setting('私聊收费设置');
        // }


        $grid->created_at('注册时间')->display(function ($time) {
            return !$time ? '-' : date('Y-m-d H:i:s', strtotime($time));
        });
        $grid->host_time('成为女用户时间')->display(function ($time) {
            return !$time ? '-' : date('Y-m-d H:i:s', $time);
        });
        $grid->updated_at('最后活跃时间')->display(function ($time) {
            return !$time ? '-' : date('Y-m-d H:i:s', strtotime($time));
        });
        $grid->userItem()->status('状态')->display(function ($data) {
            return User::STATUS[$data] ?? '';
        });
        $grid->hostInfo()->income_total('总收入')->sortable();
        $grid->hostInfo()->income_video('视频收入')->sortable();
        $grid->hostInfo()->income_gift('礼物收入')->sortable();
        $grid->hostInfo()->income_msg('私信收入')->sortable();
        $dailyHostInfo = null;
        if (request('cal_duration')) {
            $offDay = intval(request('cal_duration'));
            $start = date('Y-m-d', strtotime("-{$offDay} day"));
            $end = date('Y-m-d', strtotime("-1 day"));
            $dailyHostInfo = StatDailyHostInfo::calAverage($start, $end);
            // echo json_encode($dailyHostInfo);
        }

        foreach (StatDailyHostInfo::SHOW_FIELDS as $field => $fieldName) {
            $grid->{$field}($fieldName)->display(function ($data) use ($field, $dailyHostInfo) {
                $subfix = in_array($field, StatDailyHostInfo::RATE_FIELD) ? ' %' : '';
                if (request('cal_duration')) {
                    $data = isset($dailyHostInfo[$this->user_id]) ? $dailyHostInfo[$this->user_id][$field] : '-';
                } else {
                    $data = isset($this->dailyHostInfo[0]) ? $this->dailyHostInfo[0][$field] : '-';
                }
                if ($field == 'online_time' && $data != '-') $data = round($data / 3600, 2);
                return $data . $subfix;
            })->sortable();
        }
//        $grid->host_cate('评级')->editable('select', UserProfile::HOST_CATE);
        // $grid->host_mark('分类')->editable('select', UserProfile::HOST_MARK);

        $grid->usersRatingItem()->grade('等级')->editable('select', UsersRating::HOST_CATE);
        $grid->host_share('分成设置')->editable('select', UserProfile::HOST_SHARE)->sortable();
        //禁用导出
        $grid->disableExport();
        //禁用行选择
        $grid->disableRowSelector();
        //禁用新增
        $grid->disableCreation();
        $grid->disableActions();
        $grid->filter(function ($filter) {
            $filter->expand();
            $filter->disableIdFilter();
            $filter->column(1 / 3, function ($filter) {
                $filter->equal('user_profile_id', '用户ID');
                $filter->equal('host_cate', '女用户评级')->select(UserProfile::HOST_CATE);
            });
            $filter->column(1 / 3, function ($filter) {
                $filter->between('created_at', '注册时间')->datetime();
                $filter->equal('host_mark', '女用户分类')->select(UserProfile::HOST_MARK);
            });
            $filter->column(1 / 3, function ($filter) {
                $filter->where(function ($query) {
                }, '计算周期', 'cal_duration')->select(StatDailyHostInfo::CAL_DURATION);
//                $filter->where(function ($query) {
//                    $userIds = GuildHost::where('guild_manage_id', $this->input)->pluck('host_user_id')->toArray();
//                    $query->whereIn('user_id', $userIds);
//                }, '所属代理')->select('/get_guilds');
            });
        });

        $grid->actions(function (Grid\Displayers\Actions $actions) {
            $actions->disableDelete();
            $actions->disableView();
            $actions->disableEdit();
        });
        return $grid;
    }
}
